package api;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import lombok.SneakyThrows;
import model.Article;
import model.UserInfo;
import util.AppVar;
import util.DBUtils;
import util.ResultUtils;
import util.SessionUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * @description: 我的文章列表
 * @author: chengbaiyi
 * @create: 2022-05-20 21:28
 */
@WebServlet("/myartlist")
public class MyArticleListServlet extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Article> list = new ArrayList<>();
        String msg = "未知错误";
        // 判断登录状态
        UserInfo userInfo = SessionUtils.getLoginUser(req);
        if (userInfo != null) {
            int uid = userInfo.getUid();
            if (uid > 0) {
                // 查询数据库文章列表
                Connection connection = DBUtils.getConnection();
                String sql = "select * from article where uid=?";
                PreparedStatement statement = connection.prepareStatement(sql);
                statement.setInt(1, uid);
                ResultSet resultSet = statement.executeQuery();
                while (resultSet.next()) {
                    String context = resultSet.getString("context");
                    Article article = new Article();
                    article.setAid(resultSet.getInt("aid"));
                    article.setTitle(resultSet.getString("title"));
                    article.setContext(context);
                    // 简介
                    int subLen = Math.min(20, context.length());
                    article.setDesc(context.substring(0, subLen).replace("#", " "));
                    String create_time = resultSet.getString("create_time");
                    article.setCreate_time(create_time.substring(0, create_time.lastIndexOf(".")));
                    article.setRead_count(resultSet.getInt("read_count"));
                    article.setUid(resultSet.getInt("uid"));
                    article.setUid(resultSet.getInt("state"));
                    list.add(article);
                }
                msg = "";
                DBUtils.close(resultSet, statement, connection);
            } else {
                msg = "非法参数！";
            }
        } else {
            msg = "请先登录！";
        }
        resp.setContentType(AppVar.RESPONSE_CONTENTTYPE_JSON);
        resp.getWriter().println(JSONUtil.toJsonStr(ResultUtils.toResult(200, list, msg)));
    }
}
